import { DateTime } from 'luxon'
import { BaseModel, belongsTo, column } from '@adonisjs/lucid/orm'
import type { BelongsTo } from '@adonisjs/lucid/types/relations'
import Member from '#models/member'
import CardRight from '#models/card_right'
import SalesOrder from '#models/sales_order'

export default class MemberCard extends BaseModel {
  @column()
  declare fkSalesOrderId: number

  @column()
  declare fkMemberId: number

  @column()
  declare fkRightsId: number

  @column()
  declare name: string

  @column()
  declare discount: number

  @column()
  declare actualStoreAmount: number

  @column()
  declare actualGiftAmount: number

  @column()
  declare actualPrice: number

  @column()
  declare initJson: object

  @column()
  declare balance: number

  @column()
  declare giftBalance: number

  @column.dateTime()
  declare startDate: DateTime

  @column.dateTime()
  declare endDate: DateTime

  @column()
  declare status?: number

  @column()
  declare memo?: string

  @belongsTo(() => SalesOrder)
  declare sales: BelongsTo<typeof SalesOrder>

  @belongsTo(() => Member)
  declare member: BelongsTo<typeof Member>

  @belongsTo(() => CardRight)
  declare rights: BelongsTo<typeof CardRight>

  static add(salesOrder: SalesOrder, data: any[]) {
    const newDate = data.map(({ id, salePrice, ...item }) => ({
      ...item,
      fkShopId: salesOrder.fkShopId,
      fkSalesOrderId: salesOrder.id,
      fkMemberId: salesOrder.fkMemberId!,
      fkRightsId: id,
      actualPrice: salePrice,
      balance: item.actualStoreAmount,
      giftBalance: item.actualGiftAmount,
      startDate: DateTime.now(),
      endDate: DateTime.now().plus({ [`${item.expUnit}s`]: item.expNum }),
    }))

    return this.createMany(newDate)
  }
}
